<?php

namespace app\queue\stomp;

use app\queue\BaseConsumer;
use common\model\UserModel;
use common\service\ChatService;

class SendEntityDemandRelationMessageConsumer extends BaseConsumer
{

    // 要消费的队列名
    public $queue = 'send_entity_demand_relation_message';

    // 连接名，对应 config/redis_queue.php 里的连接`
    public $connection = 'default';

    /**
     *
     * @param $messageData
     * @return void
     */
    public function doConsume($messageData)
    {

        $data = $messageData['data'];
        $type = $messageData['type'] ?? "add_entity_demand_relation_message";
        try {
            $entityIds = $data["entity_ids"];
            if (empty($entityIds)) {
                return;
            }
            $demandId = $data["demand_id"];
            $demandTypeList = $data['demand_type_list'] ?? [];
            //找到相关的群
            $chatService = ChatService::getInstance();
            $chat = $chatService->selectBatchEntityChat($entityIds);

            if (!empty($chat)) {
                //去重
                $chat = array_column(array_values($chat), null, 'global_id');

                //邀请进群
                teamones_request('teamones-im', 'oauth/invite_chat_user', [
                    'data' => [
                        'chat_global_id' => array_keys($chat),
                        'user_id' => [request()->getUnionUserId()]
                    ]
                ]);

                $user = model(UserModel::class)->field("union_id as id,name")->find(request()->getUserId());

                $message = [
                    "type" => $type,
                    "replace" => ["user" => $user, "demand_id" => $demandId, "demand_type" => $demandTypeList,]
                ];

                if ($type === "delete_entity_demand_relation_message") {
                    $message["replace"] = ["user" => $user, "demand_id" => $demandId];
                }

                //发送需求提示消息
                foreach ($chat as $chatItem) {
                    $chatService->pushEntityTaskMessage($message, $chatItem);
                }
            }

        } catch (\Throwable $e) {
            trace(format_exception_info($e), "ERR");
        }
    }

}
